<?php

namespace lib\redis;

use lib\Singleton;
use app\common\facade\Log;

class RedisCache {
    use Singleton;
    private static $redis = null;

    /**
     * redis实例化
     * @param int $conId
     * @param string $host
     * @param int $port
     * @param string $pwd
     */
    public function __construct(int $conId,string $host, int $port = 6379, string $pwd = '') {
        $con = new \Redis();
        try {
            $con->connect($host, $port, 5);
        } catch (\Exception $e) {
            Log::info('连接Redis异常 | msg:' . $e->getMessage());
        }

        if (!empty($pwd)) {
            try {
                $con->auth($pwd);
            } catch (\Exception $e) {
                Log::info('连接Redis异常 | msg:' . $e->getMessage());
            }
        }
        self::$redis[$conId] = $con;
    }

    public static function instance(int $conId,array $configs): \Redis {
        if (!self::$redis[$conId]) {
            self::getInstance($conId,$configs['api_redis_host_name'], $configs['api_redis_hostport'], $configs['api_redis_password']);
        }
        $redis= self::$redis[$conId];
        $redis->select($configs['api_redis_database']);
        return $redis;
    }
}
